package ru.ya.kolemik;

import java.awt.Component;
import java.awt.MenuItem;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;

public class CommandMenu extends MenuItem implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3104241835206371381L;

	private final TrayCommand command;

	private Process currentProcess;

	private final JOptionPane pane;

	public CommandMenu(TrayCommand command) {
		super(command.getLabel());
		this.command = command;
		this.addActionListener(this);
		this.pane = new JOptionPane();
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		if (!this.equals(event.getSource())) {
			System.out.println("Unexpected event source");
			return;
		}
		synchronized (this) {
			if (currentProcess != null) {
				// killing process
				if (JOptionPane.showConfirmDialog(pane,
						"Are you sure to kill command \"" + command.getLabel()
								+ "\"", "Kill command",
						JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
					command.stop();
				}
				return;
			}
		}
		try {
			command.start();
			currentProcess = command.getProcess();
			setLabel(command.getLabel() + "(Runnig...)");
			new Thread() {
				public void run() {
					int exitStatus = -1;
					try {
						exitStatus = currentProcess.waitFor();
						System.out.println("Process exited with status = "
								+ exitStatus);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						synchronized (CommandMenu.this) {
							currentProcess = null;
						}
						setLabel(command.getLabel());
					}
				}
			}.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
